package com.aurora.demo.service;

import com.aurora.demo.api.param.QueryParam;
import com.aurora.demo.repository.MetaRepository;
import com.aurora.demo.entity.Meta;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MetaService {

    @Autowired
    private MetaRepository metaRepository;

    //根据查询参数获取目标图片名集合
    public List<String> getNameBySelective(QueryParam queryParam) {
        List<Meta> metas;
        metas = metaRepository.findAll();

        //根据起止时间过滤，必须
        for(int i = metas.size() - 1;i >= 0; i --) {
            String time = metas.get(i).getTime();
            if(time.compareTo(queryParam.getStartTime()) < 0 || time.compareTo(queryParam.getEndTime()) > 0) {
                metas.remove(i);
            }
        }

        //根据波段过滤，可选
        if(queryParam.getBand() != null) {
            for(int i = metas.size() - 1; i >= 0; i --) {
                if(!metas.get(i).getBand().equals(queryParam.getBand())) {
                    metas.remove(i);
                }
            }
        }

        //根据类型过滤，可选
        if(queryParam.getManualtype() != null) {
            for(int i = metas.size() - 1; i >= 0; i --) {
                if(!metas.get(i).getManualtype().equals(queryParam.getManualtype())) {
                    metas.remove(i);
                }
            }
        }

        List<String> names = metas.stream().map(Meta::getName).collect(Collectors.toList());
        return names;
    }

    public void updateManualtype(String name, String manualtype) {
        Meta meta = metaRepository.findByName(name);
        meta.setManualtype(manualtype);
        metaRepository.save(meta);
    }

    public void save(String fileName) {
        Meta meta = new Meta();

        meta.setName(fileName.substring(0,13));
        Date date = new Date();
        meta.setTime("20" + fileName.substring(1, 7) + date.getHours() + date.getMinutes() + date.getSeconds());
        meta.setBand(fileName.substring(7,8));
        meta.setManualtype("0");

        metaRepository.save(meta);
    }

    public Meta findByName(String name) {
        return metaRepository.findByName(name);
    }
}
